<template>
  <el-container class="auth-container">
    <el-container style="display: flex; justify-content: center; align-items: center; height: 100vh;">
      <el-main>
        <el-card class="box-card" shadow="hover">
          <div class="clearfix">
            <span>新增人员</span>
          </div>
          <el-form ref="personFormRef" :model="personForm" label-width="120px" class="person-form" label-position="top">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="人员身份">
                  <el-select v-model="personForm.role" placeholder="请选择">
                    <el-option label="领队" value="领队"></el-option>
                    <el-option label="教练员" value="教练员"></el-option>
                    <el-option label="运动员" value="运动员"></el-option>
                    <el-option label="随队人员" value="随队人员"></el-option>
                    <el-option label="队医" value="队医"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="身份证号码">
                  <el-input v-model="personForm.idcard"></el-input>
                </el-form-item>
                <el-form-item label="出生日期">
                  <el-date-picker v-model="personForm.birthday" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"></el-date-picker>
                </el-form-item>
                <el-form-item label="Email">
                  <el-input v-model="personForm.email"></el-input>
                </el-form-item>
                <el-form-item label="照片">
                <el-upload class="crad" :file-list="fileList" :http-request="customUpload"
                  :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
                  list-type="picture-card" :on-success="uploadSuccess" :limit="2" :on-exceed="handleExceed"
                  style="display: flex; flex-wrap: wrap;">
                  <i class="el-upload.el-upload--picture-card" style="font-size: 24px; line-height: 90px; width: 90px; height: 90px;"></i>
                </el-upload>
                <el-dialog v-model="dialogVisible" :title="dialogTitle">
                  <img :src="dialogImageUrl" alt="预览图片" style="width: 90px">
                </el-dialog>
              </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveAndClose" >关闭窗口回到人员管理</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名">
                  <el-input v-model="personForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="personForm.sex">
                    <el-radio value="男" size="large">男</el-radio>
                    <el-radio value="女" size="large">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="组别名称">
                <el-select v-model="personForm.matchesGroupId" placeholder="请选择" @change="handleGroupChange">
                  <el-option v-for="group in groups" :key="group.id" :label="getGroupLabel(group)"
                    :value="group.id"></el-option>
                </el-select>
              </el-form-item>
                <el-form-item label="手机号码">
                  <el-input v-model="personForm.phone"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveAndContinue"  class="button-right" >保存并继续添加</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm" class="button" style="margin-top: 20px">填写完成报名</el-button>
                  </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { reactive, ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useTeamStore } from '../store/teamgroupid.js'
import { useMatchIdStore } from '../store/matchid.js';
import { ElMessage } from 'element-plus';

const teamGroupId = useTeamStore().teamGroupId;

const matchStore = useMatchIdStore();

const fileList = ref([]);

const router = useRouter()

const matchid = matchStore.matchId;

const groups = ref([]);

const groupid = ref('');

const personForm = reactive({
  role: '',
  idcard: '',
  birthday: '',
  email: '',
  userName: '',
  sex: '',
  phone: '',
  image: '',
  matchesGroupId:'',
  teamGroupId: teamGroupId
});

const token = localStorage.getItem('userToken');

// 获取组别信息渲染页面
const getGroupLabel = (group) => {
  return `${group.groupname} - 出生日期: ${group.minBirthDay.slice(0, 10)} 至 ${group.maxBirthDay.slice(0, 10)}`;
};

//添加人员，并提交
const saveAndContinue = async () => {
  if(!personForm.matchesGroupId){
    ElMessage.error('请选择组别');
    return;
  }else{
    groupid.value = groups.value.find(group => group.id === personForm.matchesGroupId);
    if(groupid.value.sex == 1){
      if(personForm.sex != '男'){
        ElMessage.error('性别与组别不符，请选重新选择');
        return;
      }
    }else if(groupid.value.sex == 0){
      if(personForm.sex != '女'){
        ElMessage.error('性别与组别不符，请选重新选择');
        return;
      }
    }
  }

  if(personForm.birthday){
    groupid.value = groups.value.find(group => group.id === personForm.matchesGroupId);
    const maxBirthDay = new Date(groupid.value.maxBirthDay);
    const minBirthDay = new Date(groupid.value.minBirthDay);
    const personFormBirthday = new Date(personForm.birthday);
    const isBirthdayValid = personFormBirthday >= maxBirthDay && personFormBirthday <= minBirthDay;
    if (!isBirthdayValid) {
      ElMessage.error('年龄不在组别年龄范围内');
      return; // 阻止表单提交
    }
  }
    
  
  // 验证身份证号码
  if (/^[1-9]\d{17}[0-9X]$/.test(personForm.idcard)) {
    ElMessage.error('身份证号码不正确');
    return;
  }

  // 验证性别
  var genderDigit = parseInt(personForm.idcard.charAt(16), 10); // 获取第17位数字
    if ((genderDigit % 2 === 0 && personForm.sex !== '女') || (genderDigit % 2 !== 0 && personForm.sex !== '男')) {
        ElMessage.error('性别与身份证号码不符');
        return;
    }

    var birthYear = personForm.idcard.substring(6, 10);
    var birthMonth = personForm.idcard.substring(10, 12);
    var birthDay = personForm.idcard.substring(12, 14);

    // 将身份证号码中的日期转换为日期对象
    var birthDate = new Date(birthYear + '-' + birthMonth + '-' + birthDay);

    // 将用户填写的生日转换为日期对象
    var userBirthDate = new Date(personForm.birthday);

    // 验证生日是否一致
    if (userBirthDate.getFullYear() !== birthDate.getFullYear() ||
        userBirthDate.getMonth() + 1 !== birthDate.getMonth() + 1 ||
        userBirthDate.getDate() !== birthDate.getDate()) {
        ElMessage.error('生日与身份证号码不符');
        return;
    }


  // 验证手机号
  if (!/^[1]\d{10}$/.test(personForm.phone)) {
    ElMessage.error('手机号必须是11位数字');
    return;
  }

  // 验证邮箱
  if (!/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(personForm.email)) {
    ElMessage.error('请输入正确的邮箱地址');
    return;
  }
  if (!personForm.sex) {
    
  }
  try {
  const response = await axios.post('http://back1.idcfengye.com:15173/competition/staff/add', personForm, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  if (response.data.success) {
    ElMessage.success('添加成功！');
  }
} catch (error) {
  ElMessage.error(error.response.data.msg || '添加失败，请稍后再试');
}
}

//添加人员完毕，前往下一步
const submitForm= () => {
  router.push({ path:'/home/solopractice' });
}

const saveAndClose = () => {
  router.push('/home/personnel');
}

const searchForm = ref({
  name: '',
})

const tableData = ref([
  // 你的表格数据
])

///获取当前比赛的组别信息
async function fetchgroup() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    groups.value = response.data.matchgroup;

  } catch (error) {
    console.error('Failed to fetch projects:', error);
  }
}

fetchgroup();

//处理文件上传成功事件
const handleGroupChange = () => {
  const selectedGroup = groups.value.find(group => group.groupname === groupid.value);

    if (selectedGroup) {
    personForm.matchesGroupId = selectedGroup.id;
    if(!personForm.birthday){
      ElMessage.error('请先填写出生日期');
    }
    if (!personForm.sex) {
      ElMessage.error('请先填写性别');
    }

    // 检查性别是否符合
    if((selectedGroup.sex==0 && personForm.sex=='女')){

    }else if((selectedGroup.sex==1 && personForm.sex=='男')){
     
    }else if(selectedGroup.sex !== 2){
      ElMessage.error('性别与组别要求不符');
      groupid.value='';
      return;
    }
   
    
    // 检查出生日期是否在范围内
    const minDate = new Date(selectedGroup.minBirthDay);
    const maxDate = new Date(selectedGroup.maxBirthDay);
    const birthDate = new Date(personForm.birthday);

    if (birthDate < minDate || birthDate > maxDate) {
      ElMessage.error('年龄与该组别不符合');
      groupid.value='';
      return;
    }
  }
}

watch(() => groupid.value, (newValue) => {
  // 当选中的组别名称变化时，找到对应的 id 并赋值给 personForm.matchesGroupId
  const selectedGroup = groups.value.find(group => group.groupname === newValue);  
  if (selectedGroup) {
    personForm.matchesGroupId = selectedGroup.id;
  }
}, { immediate: true });

// 对话框可见性
const dialogVisible = ref(false);
// 对话框标题
const dialogTitle = ref('图片预览');
// 对话框中显示的图片URL
const dialogImageUrl = ref('');
// 图片地址，对话框中显示的图片URL
function handlePreview(file) {
  // 设置对话框标题和图片URL
  dialogTitle.value = file.name;
  dialogImageUrl.value = file.url;
  // 显示对话框
  dialogVisible.value = true;
}

// 上传文件
function customUpload(file) {  
  const formData = new FormData();
  formData.append('file', file.file);

  const token = localStorage.getItem('userToken');
  const config = {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'multipart/form-data',
    },
  };

  axios.post('http://back1.idcfengye.com:15173/competition/upload', formData, config)
    .then(response => {
      // 假设服务器返回的文件URL在response.data.url
      const fileUrl = response.data.path;
      const uploadedFile = {
        name: file.file.name,
        url: fileUrl,
      };
      personForm.image = fileUrl;
      fileList.value.push(uploadedFile);
      ElMessage.success('文件上传成功');
    })
    .catch(error => {
      ElMessage.error('文件上传失败');
      console.error('Upload error:', error);
    });
}

// 移除文件
function handleRemove(file, fileList) {
  // 从fileList中移除文件
  const index = fileList.value.findIndex(f => f.name === file.name);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }
}
// 移除文件前的确认
function beforeRemove(file, fileList) {
  // 确认是否移除文件
  const confirmMessage = `确定要移除文件 ${file.name} 吗?`;
  if (window.confirm(confirmMessage)) {
    // 用户点击了确认，可以继续移除文件
    return true;
  } else {
    // 用户点击了取消，阻止文件移除
    return false;
  }
}
// 上传成功后的回调
function uploadSuccess(response, file, fileList) {
  // 上传成功后的回调
  console.log('Upload success:', response);
}
// 上传失败后的回调
function handleExceed(files, fileList) {
  ElMessage.warning(`最多只能上传两张照片`);
}
</script>

<style scoped>
::v-deep .el-upload--picture-card {
  --el-upload-picture-card-size: 90px;
}
::v-deep .el-upload-list--picture-card {
  --el-upload-list-picture-card-size: 90px;
}
.auth-container {
  width: 100%;
}

span {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  text-align: center;
  margin-bottom: 20px;
}

.box-card {
  border-radius: 12px;
  background-color: #a3c9c7;
  width: 76%;
  margin-left: 12%;
}

.person-form {
  margin-bottom: 20px;
}

.button-right,button {
  border-radius: 10px;
  width: 100%;
  margin: 0 auto;
  color: white;
}

.button-right {
  margin-top: 58px;
}
</style>